﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace KindleComic.Core
{
    public static class XMLOpteration
    {
        private static string fileName = "downloadInfo.xml";
        private static readonly object o = new object();
        /// <summary>
        /// 生成xml文件
        /// </summary>
        /// <param name="fileName"></param>
        public static void GenderXMLFile()
        {
            if (!File.Exists(fileName))
            {
                XDocument xdoc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("root"));
                xdoc.Save(fileName);
            }
        }

        public static bool IsExistsNode(Func<XElement, bool> func)
        {
            lock (o)
            {
                XDocument doc = XDocument.Load(fileName);
                var root = doc.Root;
                return func(root);
            }
        }

        public static XElement Query()
        {
            lock (o)
            {
                XDocument doc = XDocument.Load(fileName);
                var root = doc.Root;
                return root;
            }
        }

        public static void AddElement(XElement xele)
        {
            lock (o)
            {
                XDocument doc = XDocument.Load(fileName);
                var root = doc.Root;
                root.Add(xele);
                doc.Save(fileName);
            }
        }

        public static void AppendElement(Func<XElement, XElement> func, XElement xElement)
        {
            lock (o)
            {
                XDocument doc = XDocument.Load(fileName);
                var root = doc.Root;
                func(root).Add(xElement);
                //root.Add(xele);
                doc.Save(fileName);
            }
        }

        public static void Update(Action<XElement> action)
        {
            lock (o)
            {
                XElement element = XElement.Load(fileName);
                action(element);
                element.Save(fileName);
            }
        }
    }
}
